/**
 * Copyright (C) 2024-2030 Super BilGen & 超亿时代信息技术股份有限公司.All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.com.yang.controller;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.zip.GZIPInputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;


//import cn.hutool.core.codec.Base64;

/**
 * @Model cn.com.yang.controller.TestBase64Controller
 * @Desc  TODO
 * @author yangyijin
 * @since 2024年11月26日-下午2:56:21
 */
@RestController
@RequestMapping("/api")
public class TestBase64Controller {
	private Logger logger =LoggerFactory.getLogger(TestBase64Controller.class);

	@GetMapping("/base64/de")
	public String deCode(HttpServletRequest request,HttpServletResponse response) {
		return Base64.decodeBase64(request.getParameter("str")).toString();
	}
	
	@PostMapping("/base64/unzip")
	public String unzip(HttpServletRequest request,HttpServletResponse response) {
		
		StringBuffer buffer = new StringBuffer();
		String line="";
		try(BufferedReader reader = request.getReader()){
			while((line = reader.readLine())!=null) {
				buffer.append(line);
			}
		}catch(Exception ex){
			logger.error("获取请求内容失败:{}",ex);
		};
		String body = buffer.toString();
		logger.info("获取前端请求数据:{}",body);
		Map<String, String> reMap = JSON.parseObject(body, Map.class);
		String send =  reMap.get("base64");
//		byte[] bytes=null;
//		try {
//			bytes = send.getBytes("GBK");
//		} catch (UnsupportedEncodingException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		logger.info("isBase64:{}",Base64.isBase64(send));
//		String send ="H4sICOCSZGMAAzIwMjIxMTA0MzU4MDQxODU3ODIxMjEzc3VjY2Vzcy54bWwAbZNLb1NBDIXXzG/xYmyPPTP826qo6gqVEPK4baKbRmkgiD5ACaU/ADalScVTUZHwIEC6vZ310fE539gISiwePSqS95q9J4XlrD4aXIFkJHDUkCBGz5Kg3xtu6icgXgQc/5cERO9zTJkjTGfDbd2FwGouoe3CbJLRZnIEijGCk78S9eqjt5ciCxx/Ht+9/GCDQgKnbYl4ePOt2p1sIQS1LLElSYnh8OTFZa8LgoHBpbYLRXN5+7OzDyjqweUi8ST/GqGqzZ+sTmsQiw4OfZNcsMqcYH7ZWYw7oCW5Q7xHV4U4wKI/X/c/gaRspZGa7JBjVrbWw+3yIwT02TTc9OEoHCIMeof1ag4soWjagINEy9OtVnsQRMosAUrFAAmLS2SfPUzP6u70BzD/GaXNOCmFSGia6vr8GIKSscEHEFut91+mdf3d/lKKJjUjR2vlBaqv8/V4CcKKpsnNyCycU4J3V8f98R1QIENIvjWLs8LF3vjgrGN47Gsd3cNcIBLD6/XsdHYKHMuXE7V8lNUwj/YLHmXLQ9z6UsnF5+Dp0LYrGhtHocVHRE0z2Z7fQtYikdY1iJFfXY82gyWwrYlpHlhki1lt+/t2d1mo3F0bs3qCwaa309sBS2/3QO1VpohwcbO8rXYhkW2Jc+75q+Hes8Xi12NKj6qzo5PRpnezWyGrXcxvIbWjBQEEAAA=";
		byte[] bytes = Base64.decodeBase64(send.getBytes());
//		byte[] bytes =  Base64.decode(send);
		
		unGizp(bytes);
		
//		try {
//			String deStr = gzipDecompress(bytes);
//			logger.info("解码结果：{}",deStr);
//		} catch (IOException ex) {
//			logger.error("解码异常:{}",ex);
//		}
		
		return unGizp(bytes);
	}
	
	/**
	 * java.util.zip.ZipException: Not in GZIP format(不解码base64报错)
	 * java.util.zip.ZipException: invalid distance too far back(解码base64报错)
	 * @return
	 */
	private String unGizp(byte[] gzipbytes) {
		try(ByteArrayInputStream bis = new ByteArrayInputStream(gzipbytes);
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			GZIPInputStream input =new GZIPInputStream(bis);){
			byte[] buffer = new byte[gzipbytes.length];
            int len;
            while ((len = input.read(buffer)) >= 0) {
                out.write(buffer, 0, len);
            }
			String deStr = new String(out.toByteArray(),"GBK");
			logger.info("解码结果:{}",deStr);
			return deStr;
//			return new String(Base64.decode(out.toByteArray()));
		}catch(Exception ex) {
			logger.error("解码异常:{}",ex);
		}
		return "deStr";
	}
	/**
	 * 报错1：java.io.IOException: Gzip-compressed data is corrupt (不解码base64报错)
	 * 报错2：java.io.IOException: Input is not in the .gz format (解码base64报错)
	 * @param compressedData
	 * @return
	 * @throws IOException
	 */
	private  String gzipDecompress(byte[] compressedData) throws IOException {
        if (compressedData == null || compressedData.length == 0) {
            return null;
        }
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(compressedData);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try (GzipCompressorInputStream gzipInputStream = new GzipCompressorInputStream(byteArrayInputStream)) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = gzipInputStream.read(buffer)) > 0) {
                byteArrayOutputStream.write(buffer, 0, len);
            }
        }
        return byteArrayOutputStream.toString("GBK");
    }
}
